package org.ewicom.ppsaddressbook.model;

import java.util.ArrayList;
import java.util.List;

import org.ewicom.ppsaddressbook.DatabaseHelper;
import org.ewicom.ppsaddressbook.PPSAddressBook.PersonColumns;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class PersonDataSource {

	private SQLiteDatabase db;
	private DatabaseHelper dbHelper;

	private static final String[] PERSON_PROJECTION = new String[] {
			PersonColumns._ID, PersonColumns.POSITION, PersonColumns.PERSON,
			PersonColumns.PHONE, PersonColumns.EMAIL, };

	private static final int COLUMN_INDEX_PERSON_ID = 0;
	private static final int COLUMN_INDEX_PERSON_POSITION = 1;
	private static final int COLUMN_INDEX_PERSON_PERSON = 2;
	private static final int COLUMN_INDEX_PERSON_PHONE = 3;
	private static final int COLUMN_INDEX_PERSON_EMAIL = 4;

	public PersonDataSource(Context context) {
		dbHelper = new DatabaseHelper(context);
	}

	public void open() throws SQLException {
		db = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}

	public List<Person> getAllPersons() {
		List<Person> persons = new ArrayList<Person>();

		Cursor cursor = db.query(PersonColumns.PERSON_TABLE_NAME,
				PERSON_PROJECTION, null, null, null, null,
				PersonColumns.DEFAULT_SORT_ORDER);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Person person = CursorToPerson(cursor);
			persons.add(person);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return persons;
	}

	public List<Person> getPersonsByUnitId(long unitId) {
		List<Person> persons = new ArrayList<Person>();

		Cursor cursor = db.query(PersonColumns.PERSON_TABLE_NAME,
				PERSON_PROJECTION,
				PersonColumns.UNIT_ID + "=" + String.valueOf(unitId), null,
				null, null, PersonColumns.DEFAULT_SORT_ORDER);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Person person = CursorToPerson(cursor);
			persons.add(person);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return persons;
	}

	private Person CursorToPerson(Cursor cursor) {
		Person person = new Person();

		person.setId(cursor.getLong(COLUMN_INDEX_PERSON_ID));
		person.setPosition(cursor.getString(COLUMN_INDEX_PERSON_POSITION));
		person.setPerson(cursor.getString(COLUMN_INDEX_PERSON_PERSON));
		person.setPhone(cursor.getString(COLUMN_INDEX_PERSON_PHONE));
		person.setEmail(cursor.getString(COLUMN_INDEX_PERSON_EMAIL));

		return person;
	}

}
